<template>
  <BoTable
    :columns="_columns"
    :request="labelList"
    :row-selection="rowSelection"
    row-key="bizHostId"
    ref="tableRef"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
        <Button type="primary" @click="onPacket"> 主机分组 </Button>
        <Button :disabled="!selectKeys.length" @click="onDelete"> 删除 </Button>
      </Space>
    </template>
  </BoTable>

  <FormModal :tabs="_item" :model="formState">
    <template #infoBtn>
      <div class="custom_btn">
        <Button type="primary" @click="onSubmit('info')"> 保存 </Button>
      </div>
    </template>
    <template #loginBtn>
      <div class="custom_btn">
        <Button type="primary" @click="onSubmit('login')"> 保存 </Button>
      </div>
    </template>
    <template #details>
      <FormItemRest>
        <customFrom
          v-model:info="formState.jsonConfig"
          :formState="formState"
          :formRef="formRef"
        />
      </FormItemRest>
    </template>
  </FormModal>
  <customDrawer
    v-model:visible="visible"
    title="业务系统分组配置"
    width="70vw"
    :destroyOnClose="true"
    :closable="false"
  />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, FormItemRest, Modal, Space, message } from 'ant-design-vue';
import customDrawer from '@/components/customDrawer/index.vue';
import customFrom from '@/components/customFrom/index.vue';
import {
  GroupDelete,
  bizHostAdd,
  bizHostUpdate,
  groupSelectList,
  labelList,
  labelSelectList,
  treeList,
} from './api';

const { sysHostStatusEnum, sysHostProtocolOptions } = useDicts([
  'sys_host_status',
  'sys_host_protocol',
]);
const { FormModal, open, formRef } = useFormModal({
  size: 'small',
  // column: 1,
});
const formState = ref({
  authType: '1',
  jsonConfig: [],
});
const groupOptions = ref([]);
const labelOptions = ref([]);
const treeOptions = ref([]);
const getInfo = async () => {
  const group = await groupSelectList();
  groupOptions.value = listToOption(group.data, 'groupName', 'groupId', 'int');
  const label = await labelSelectList();
  labelOptions.value = listToOption(label.data, 'labelName', 'labelId', 'int');
  const tree = await treeList({
    isOs: 1,
    ruleType: 0,
  });
  treeOptions.value = addDisabledToParents(tree.data);
};
getInfo();
const tableRef = ref();
const onAdd = () => {
  formState.value = {
    authType: '1',
    jsonConfig: [],
  };
  open({
    title: '新增',
    // hideFooter: true,
    request: async (params: any) => {
      formState.value.hostConfig = JSON.stringify(formState.value.jsonConfig);
      await bizHostAdd(formState.value);
      tableRef.value.refresh();
    },
    defaultValue: formState.value,
  });
};

const onSubmit = async (type) => {
  const query = {
    info: {
      params: ['name', 'manufacturer', 'type', 'ip'],
      api: () => {},
    },
    login: {
      params: ['address', 'username', 'password'],
      api: () => {},
    },
  };
  const queryParams = await formRef.value.validateFields(query[type].params);
  const result = await query[type].api(queryParams);
  console.log(result, 'type');
};

const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const _columns = computed<BoTableProps['columns']>(() => [
  // {
  //   title: '主机ID',
  //   dataIndex: 'bizHostId',
  // },
  {
    title: '主机名称',
    dataIndex: 'hostName',
  },
  {
    title: '主机编码',
    dataIndex: 'hostCode',
  },
  {
    title: '主机协议',
    dataIndex: 'hostProtocol',
  },
  {
    title: '主机分组',
    dataIndex: 'groupIds',
    hideInSearch: true,
    customRender: ({ record }) => {
      const label = record.groupIds.map(
        (i) => groupOptions.value.find((item) => item.value === i)?.label,
      );
      return label;
    },
  },
  {
    title: '系统类型',
    dataIndex: 'sysTypeId',
    hideInTable: true,
  },
  {
    title: '系统架构',
    dataIndex: 'sysFramework',
    hideInTable: true,
  },
  {
    title: '主机地址',
    dataIndex: 'hostAddress',
  },
  {
    title: '主机标签',
    dataIndex: 'labelIds',
  },
  {
    title: '主机状态',
    dataIndex: 'status',
    valueType: 'select',
    valueEnum: sysHostStatusEnum.value,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '修改人',
    dataIndex: 'updateBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '修改',
        onClick(record) {
          formState.value = {
            ...record,
            jsonConfig: JSON.parse(record.hostConfig),
          };
          open({
            title: (type) => (type === 'info' ? '详情' : '编辑'),
            modalType: 'info',
            request: async (params: any) => {
              params.hostConfig = JSON.stringify(formState.value.jsonConfig);
              await bizHostUpdate(params);
            },
            defaultValue: formState.value,
          });
        },
      },
    ],
  },
]);
const _item = computed<BoFormProps['columns']>(() => {
  return [
    {
      tab: '主机信息',
      key: 1,
      columns: [
        {
          title: '主机名称',
          valueType: 'input',
          dataIndex: 'hostName',
          fieldProps: {
            placeholder: '请输入主机名称',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机名称',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机编码',
          valueType: 'input',
          dataIndex: 'hostCode',
          fieldProps: {
            placeholder: '请输入主机编码',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机编码',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机地址',
          valueType: 'input',
          dataIndex: 'hostAddress',
          fieldProps: {
            placeholder: '请输入主机地址',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机地址',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机协议',
          valueType: 'select',
          dataIndex: 'hostProtocol',
          fieldProps: {
            placeholder: '请输入主机协议',
            options: sysHostProtocolOptions.value,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机协议',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '系统类型',
          valueType: 'treeSelect',
          dataIndex: 'sysTypeId',
          fieldProps: {
            placeholder: '请输入系统类型',
            treeData: treeOptions.value,
            fieldNames: {
              children: 'children',
              label: 'name',
              key: 'id',
              value: 'id',
            },
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入系统类型',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '系统架构',
          valueType: 'input',
          dataIndex: 'sysFramework',
          fieldProps: {
            placeholder: '请输入系统架构',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入系统架构',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机分组',
          valueType: 'select',
          dataIndex: 'groupIds',
          fieldProps: {
            placeholder: '请输入主机分组',
            mode: 'multiple',
            options: groupOptions.value,
            maxTagCount: '1',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机分组',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机标签',
          valueType: 'select',
          dataIndex: 'labelIds',
          fieldProps: {
            placeholder: '请输入主机标签',
            mode: 'multiple',
            options: labelOptions.value,
            maxTagCount: '1',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机标签',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '主机描述',
          valueType: 'textarea',
          dataIndex: 'remark',
          fieldProps: {
            placeholder: '请输入主机描述',
            rows: 4,
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入主机描述',
                trigger: 'blur',
              },
            ],
          },
        },
        // {
        //   title: '',
        //   valueType: 'infoBtn',
        //   dataIndex: 'infoBtn',
        //   formItemProps: {
        //     wrapperCol: { span: 24 },
        //   },
        // },
      ],
    },
    {
      tab: '规格配置',
      key: 2,
      columns: [
        {
          title: '',
          valueType: 'input',
          dataIndex: 'details',
          formItemProps: {
            wrapperCol: { span: 24 },
          },
        },
      ],
    },
    {
      tab: '登录信息',
      key: 3,
      columns: [
        {
          title: '端口',
          valueType: 'input',
          dataIndex: 'hostPort',
          fieldProps: {
            placeholder: '请输入端口',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入端口',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '用户名',
          valueType: 'input',
          dataIndex: 'userName',
          fieldProps: {
            placeholder: '请输入用户名',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入用户名',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '认证方式',
          valueType: 'radio',
          dataIndex: 'authType',
          fieldProps: {
            placeholder: '请选择认证方式',
            options: [
              {
                label: '密码认证',
                value: '1',
              },
              {
                label: '密钥认证',
                value: '2',
              },
            ],
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请选择认证方式',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '密码',
          valueType: 'input',
          dataIndex: 'password',
          fieldProps: {
            placeholder: '请输入密码',
            type: 'password',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入密码',
                trigger: 'blur',
              },
            ],
          },
        },
        {
          title: '连接超时时间',
          valueType: 'input',
          dataIndex: 'timeout',
          fieldProps: {
            placeholder: '请输入连接超时时间',
            addonAfter: 'ms',
          },
          formItemProps: {
            rules: [
              {
                required: true,
                message: '请输入连接超时时间',
                trigger: 'blur',
              },
            ],
          },
        },
        // {
        //   title: '',
        //   valueType: 'loginBtn',
        //   dataIndex: 'loginBtn',
        //   formItemProps: {
        //     wrapperCol: { span: 24 },
        //   },
        // },
      ],
    },
  ];
});

const onDelete = () => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选中项数据吗？`,
    onOk: async () => {
      await GroupDelete(selectKeys.value.join());
      tableRef.value.refresh();
      message.success('操作成功');
      selectKeys.value = [];
    },
  });
};
const visible = ref(false);

const onPacket = () => {
  visible.value = true;
};

const addDisabledToParents = (tree) => {
  const processNode = (node) => {
    if (node.children && node.children.length > 0) {
      node.disabled = true;
      node.children.forEach(processNode);
    }
  };
  tree.forEach(processNode);
  return tree;
};
</script>

<style scoped lang="scss">
.custom_btn {
  display: flex;
  justify-content: flex-end;
  :deep(.ant-btn) {
    width: 561px;
  }
}
</style>

<route lang="json">
{
  "meta": {
    "title": "业务系统"
  }
}
</route>
